package renguanyu.app.tools.model.anjuke;

import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

/**
 * 安居客社区数据
 */
public class CommunityData {

	private String word;
	private String commId;
	private String url;
	private String host;
	private int port;
	private int pageDuration;
	private int communityDuration;

	public CommunityData() {
	}

	public CommunityData(String word, String commId, int durationSecond, int communityDuration) {
		this.word = word;
		this.url = this.url.replace("{q}", this.word);
		this.url = this.url + "&comm_id=" + commId;
		this.pageDuration = durationSecond;
		this.communityDuration = communityDuration;
	}

	public CommunityData(String host, int port, String word, String commId, int durationSecond, int communityDuration) {
		this.host = host;
		this.port = port;
		this.word = word;
		this.url = this.url.replace("{q}", this.word);
		this.url = this.url + "&comm_id=" + commId;
		this.pageDuration = durationSecond;
		this.communityDuration = communityDuration;
	}

	public CommunityData(String word, int durationSecond, int communityDuration) {
		this.word = word;
		this.url = this.url.replace("{q}", this.word);
		this.pageDuration = durationSecond;
		this.communityDuration = communityDuration;
	}

	public CommunityData(String host, int port, String word, int durationSecond, int communityDuration) {
		this.host = host;
		this.port = port;
		this.word = word;
		this.url = this.url.replace("{q}", this.word);
		this.pageDuration = durationSecond;
		this.communityDuration = communityDuration;
	}

	private String errorMsg = "系统检测到您正在使用网页抓取工具访问安居客网站，请卸载删除后访问";
	private String fastCallMsg = "访问过于频繁，本次访问做以下验证码校验。";
	private String verifyMsg = "向右滑动滑块填充拼图";

	public void save() throws Exception {
		int n = 1;
		while (true) {
			String targetUrl = url.replace("o5", "o5-p" + n);
			Connection connect = Jsoup.connect(targetUrl);
			if (host != null) {
				connect = connect.proxy(host, port);
			}
			Map<String, String> header = JsoupUtil.getHeader();
			Connection headers = connect.headers(header);
			Document doc = headers.get();
			String html = doc.html();
			// 是否存在异常
			boolean contains = html.contains(errorMsg);
			if (contains) {
				Exception exception = new Exception(errorMsg);
				DataCollect.appendExecuteLog(exception.toString());
				throw exception;
			}
			// 是否存在滑块
			Element verifyInfo = doc.selectXpath("//div[@class='verify_info']").first();
			if (verifyInfo != null) {
				System.err.println(targetUrl);
				DataCollect.appendExecuteLog(String.format("ERROR >> %s \n", targetUrl));
				Exception exception = new Exception(verifyMsg);
				DataCollect.appendExecuteLog(String.format("%s \n", exception.toString()));
				throw exception;
			}
			// 是否存在访问频繁
			Element fastCall = doc.selectXpath("//div[@id='@@xxzlGatewayUrl']").first();
			if (fastCall != null) {
				System.err.println(targetUrl);
				DataCollect.appendExecuteLog(String.format("ERROR >> %s \n", targetUrl));
				Exception exception = new Exception(fastCallMsg);
				DataCollect.appendExecuteLog(String.format("%s \n", exception.toString()));
				throw exception;
			}
			// 采集数据
			Elements elements = doc.selectXpath("//div[@tongji_tag='fcpc_ersflist_gzcount']");
			for (Element element : elements) {
				AnjukeListElement anjukeListElement = new AnjukeListElement();
				anjukeListElement.setCode(element);
				anjukeListElement.setTitle(element);
				anjukeListElement.setAnxuan(element);
				anjukeListElement.setStructure(element);
				anjukeListElement.setArea(element);
				anjukeListElement.setToward(element);
				anjukeListElement.setFloor(element);
				anjukeListElement.setCreateYear(element);
				anjukeListElement.setCommunityName(element);
				anjukeListElement.setCommunityAddress(element);
				anjukeListElement.setTotalPrice(element);
				anjukeListElement.setAvgPrice(element);
				anjukeListElement.save2Mysql();
			}
			// 采集完成
			String status = String.format("SUCCESS >> %s \n", targetUrl);
			System.out.print(status);
			DataCollect.appendExecuteLog(status);
			TimeUnit.SECONDS.sleep(this.pageDuration);
			// 是否存在下一页的按钮
			// 如果不存在，说明这个页面只有1页数据，无需翻页采集
			Element nextActive = doc.selectXpath("//a[@class='next next-active']").first();
			if (nextActive == null) {
				break;
			}
			// 页面上下一页按钮，是否处于禁止状态
			// 如果是禁止，说明是最后一页了，无需继续采集
			Element clickForbid = doc.selectXpath("//a[@class='next click-forbid']").first();
			if (clickForbid != null) {
				break;
			}
			n++;
		}
		TimeUnit.SECONDS.sleep(this.communityDuration);
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public void setWord(String word) {
		this.word = word;
		this.url = this.url.replace("{q}", this.word);
	}

	public void setCommId(String commId) {
		this.commId = commId;
		this.url = this.url + "&comm_id=" + commId;
	}

	public void setPageDuration(int pageDuration) {
		this.pageDuration = pageDuration;
	}

	public void setCommunityDuration(int communityDuration) {
		this.communityDuration = communityDuration;
	}

}